package models

import (
	"context"
	"fmt"
	"sort"
	"strconv"
	"time"

	"go-papers/cache"
	orm "go-papers/database"
	"go-papers/pkg/lognew"
	"go-papers/tools"
)

type Course struct {
	CourseId   int    `json:"courseId" gorm:"type:int(11);primary_key"` // 主键id
	OrganName  string `json:"organName" gorm:"type:varchar(255);"`      // 机构名称
	BrandName  string `json:"brandName" gorm:"-"`                       // 品牌名称
	CourseCode string `json:"courseCode" gorm:"type:varchar(255);"`     // 课程代码

	CourseType     string `json:"courseType" gorm:"type:varchar(255);"`     // 课程类目 课程类别  素质教育
	CourseImage    string `json:"courseImage" gorm:"type:text;"`            // 课程类目 课程类别  素质教育
	CourseCategory string `json:"courseCategory" gorm:"type:varchar(255);"` // 学科科目 语文/数学
	CourseName     string `json:"courseName" gorm:"type:varchar(255);"`     // 课程名称

	OrganId     int    `json:"organId" gorm:"type:int(11);"`          // 授课机构
	CourseTeach string `json:"courseTeach" gorm:"type:varchar(255);"` // 授课方式 ：线上 、 线下

	CourseExpensive string `json:"courseExpensive" gorm:"type:varchar(255);"` // 是否 贵就赔 1 是 / 0 否

	CoursePrice   float64 `json:"coursePrice" gorm:"type:decimal(10,2);"`   // 授课金额
	RealPrice     float64 `json:"realPrice" gorm:"type:decimal(10,2);"`     // 授课金额 真实金额  coursePrice - discountPrice
	DiscountPrice float64 `json:"discountPrice" gorm:"type:decimal(10,2);"` // 优惠金额

	CourseTime string `json:"courseTime" gorm:"type:varchar(255);"` // 授课时间 字符串
	CourseAge  string `json:"courseAge" gorm:"type:varchar(255);"`  // 授课适合年龄 1 :0～3岁 3 :3～6岁 6 :7-12岁 9:12-18岁  12: 18岁+

	CourseVideo string `json:"courseVideo" gorm:"type:varchar(255);"` // 介绍视频 json
	CourseImg   string `json:"courseImg" gorm:"type:text;"`           // 介绍图片 json

	CourseSystem     string `json:"courseSystem" gorm:"type:text;"`     // 课程体系
	CourseSystemTxt  string `json:"courseSystemTxt" gorm:"type:text;"`  // 课程体系 文本信息
	CourseFeature    string `json:"courseFeature" gorm:"type:text;"`    // 课程特色
	CourseFeatureTxt string `json:"courseFeatureTxt" gorm:"type:text;"` // 课程特色 文本信息
	CourseTools      string `json:"courseTools" gorm:"type:text;"`      // 课程教具
	CourseToolsTxt   string `json:"courseToolsTxt" gorm:"type:text;"`   // 课程教具 文本信息
	CourseService    string `json:"courseService" gorm:"type:text;"`    // 课程服务体系
	CourseServiceTxt string `json:"courseServiceTxt" gorm:"type:text;"` // 课程服务体系 文本信息

	CourseGoal    string `json:"courseGoal" gorm:"type:text;"`           // 证明材料courseGoal
	CourseGoalTxt string `json:"courseGoalTxt" gorm:"type:text;"`        // 课程目标
	CourseListen  string `json:"courseListen" gorm:"type:varchar(255);"` // 支持旁听：courseListen  字符串类型 “0”， “1”

	CourseTransfer    string `json:"courseTransfer" gorm:"type:text;"`    // 支付转让
	CourseTransferTxt string `json:"courseTransferTxt" gorm:"type:text;"` // 支付转让 文本信息
	CourseFree        string `json:"courseFree" gorm:"type:text;"`        // 支付冻结
	CourseFreeTxt     string `json:"courseFreeTxt" gorm:"type:text;"`     // 支付冻结 文本信息
	CourseRefund      string `json:"courseRefund" gorm:"type:text;"`      // 退费规则
	CourseRefundTxt   string `json:"courseRefundTxt" gorm:"type:text;"`   // 退费规则 文本信息
	CourseLeave       string `json:"courseLeave" gorm:"type:text;"`       // 请假制度
	CourseLeaveTxt    string `json:"courseLeaveTxt" gorm:"type:text;"`    // 请假制度 文本信息

	CourseInfo   string `json:"courseInfo" gorm:"type:text;"`           // 介绍详情
	CourseFinish string `json:"courseFinish" gorm:"type:varchar(255);"` // 课程完成度

	CourseStatus     string `json:"courseStatus" gorm:"type:tinyint(1);"`       // 核准状态 1 待审核 ，3 失败 ， 5 已审核
	ApprovalAt       string `json:"approvalAt" gorm:"type:varchar(255);"`       // 核准时间
	ApprovalUserId   string `json:"approvalUserId" gorm:"type:varchar(32);"`    // 核准人用户id
	ApprovalUserName string `json:"approvalUserName" gorm:"type:varchar(255);"` // 审核核准人名称

	CourseOrderNum        int     `json:"courseOrderNum" gorm:"type:int(11);"`              // 课程订单销售数量
	CourseOrderPrice      float64 `json:"courseOrderPrice" gorm:"type:decimal(10,2);"`      // 课程订单总销售 包含佣金
	CourseOrderRefund     float64 `json:"courseOrderRefund" gorm:"type:decimal(10,2);"`     // 课程订单总退款 包含佣金 实际退还用户
	CourseOrderSurePrice  float64 `json:"courseOrderSurePrice" gorm:"type:decimal(10,2);"`  // 课程订单实际销售总额 不包含佣金
	CourseOrderSureRefund float64 `json:"courseOrderSureRefund" gorm:"type:decimal(10,2);"` // 课程订单总退款 课程退款 不包含佣金

	CreateBy     string `json:"createBy" gorm:"type:varchar(255);"`     // 创建
	UpdateBy     string `json:"updateBy" gorm:"type:varchar(255);"`     // 跟新
	CreateByName string `json:"createByName" gorm:"type:varchar(255);"` // 创建人
	UpdateByName string `json:"updateByName" gorm:"type:varchar(255);"` // 更新人

	UpdateStart string `json:"updateStart" gorm:"-"` // 跟新 起始时间
	UpdateEnd   string `json:"updateEnd" gorm:"-"`   // 跟新 结束时间

	IsDel           string `json:"isDel" gorm:"type:varchar(2);"` // 是否删除
	OrganFeature    string `json:"organFeature" gorm:"-"`
	OrganFeatureTxt string `json:"organFeatureTxt" gorm:"-"`

	OrganWt        string `json:"organWt" gorm:"-"`
	OrganLt        string `json:"organLt" gorm:"-"`
	ContrastStatus string `json:"contrastStatus" gorm:"-"`
	ContrastId     int    `json:"contrastId" gorm:"-"`
	CollectStatus  string `json:"collectStatus" gorm:"-"`
	LocationKm     string `json:"locationKm" gorm:"-"`

	OrganProvince string `json:"organProvince" gorm:"-"` // 机构省份 --
	OrganCity     string `json:"organCity" gorm:"-"`     // 城市    --
	OrganArea     string `json:"organArea" gorm:"-"`     // 区域    --
	OrganAddr     string `json:"organAddr" gorm:"-"`     // 机构详细地址 --
	OrganAddrTxt  string `json:"organAddrTxt" gorm:"-"`  // 地址json数据  --

	OrganInfo interface{} `json:"organInfo" gorm:"-"` // 地址json数据  --
	BrandInfo interface{} `json:"brandInfo" gorm:"-"` // 地址json数据  --

	DataScope   string      `json:"dataScope" gorm:"-"`
	CompareInfo interface{} `json:"compareInfo" gorm:"-"`
	Params      string      `json:"params"  gorm:"-"`
	BaseModel
}

type CourseNew struct {
	CourseId   int    `json:"courseId" gorm:"type:int(11);primary_key"` // 主键id
	OrganName  string `json:"organName" gorm:"type:varchar(255);"`      // 机构名称
	BrandName  string `json:"brandName" gorm:"type:varchar(255);"`      // 品牌名称
	CourseCode string `json:"courseCode" gorm:"type:varchar(255);"`     // 课程代码

	CourseType     string `json:"courseType" gorm:"type:varchar(255);"`     // 课程类目 课程类别  素质教育
	CourseImage    string `json:"courseImage" gorm:"type:text;"`            // 课程类目 课程类别  素质教育
	CourseCategory string `json:"courseCategory" gorm:"type:varchar(255);"` // 学科科目 语文/数学
	CourseName     string `json:"courseName" gorm:"type:varchar(255);"`     // 课程名称

	OrganId     int    `json:"organId" gorm:"type:int(11);"`          // 授课机构
	CourseTeach string `json:"courseTeach" gorm:"type:varchar(255);"` // 授课方式 ：线上 、 线下

	CourseExpensive string `json:"courseExpensive" gorm:"type:varchar(255);"` // 是否 贵就赔 1 是 / 0 否
	CourseListen    string `json:"courseListen" gorm:"type:varchar(255);"`    // 是否 贵就赔 1 是 / 0 否

	CoursePrice   float64 `json:"coursePrice" gorm:"type:decimal(10,2);"`   // 授课金额
	DiscountPrice float64 `json:"discountPrice" gorm:"type:decimal(10,2);"` // 优惠金额

	CourseTime string `json:"courseTime" gorm:"type:varchar(255);"` // 授课时间 字符串
	CourseAge  string `json:"courseAge" gorm:"type:varchar(255);"`  // 授课适合年龄 1 :0～3岁 3 :3～6岁 6 :7-12岁 9:12-18岁  12: 18岁+

	CourseInfo   string `json:"courseInfo" gorm:"type:text;"`           // 介绍详情
	CourseFinish string `json:"courseFinish" gorm:"type:varchar(255);"` // 课程完成度

	CourseStatus string `json:"courseStatus" gorm:"type:tinyint(1);"` // 核准状态 1 待审核 ，3 失败 ， 5 已审核

	CourseOrderNum        int     `json:"courseOrderNum" gorm:"type:int(11);"`              // 课程订单销售数量
	CourseOrderPrice      float64 `json:"courseOrderPrice" gorm:"type:decimal(10,2);"`      // 课程订单总销售 包含佣金
	CourseOrderRefund     float64 `json:"courseOrderRefund" gorm:"type:decimal(10,2);"`     // 课程订单总退款 包含佣金 实际退还用户
	CourseOrderSurePrice  float64 `json:"courseOrderSurePrice" gorm:"type:decimal(10,2);"`  // 课程订单实际销售总额 不包含佣金
	CourseOrderSureRefund float64 `json:"courseOrderSureRefund" gorm:"type:decimal(10,2);"` // 课程订单总退款 课程退款 不包含佣金
}

func (Course) TableName() string {
	return "course"
}

// 创建Course
func (e *Course) Create() (Course, error) {
	var doc Course
	result := orm.Eloquent.Table(e.TableName()).Create(&e)
	if result.Error != nil {
		err := result.Error
		return doc, err
	}
	doc = *e
	return doc, nil
}

func (e *Course) GetByIdV2(id int, mid int, openId string) (Course, error) {

	doc, _ := e.GetById(id)
	//根据用户查询
	var organ Organ
	organList, _ := organ.GetByID(doc.OrganId)
	doc.BrandName = organList.OrganBrand
	doc.OrganFeature = organList.OrganFeature
	doc.OrganLt = organList.OrganLt
	doc.OrganWt = organList.OrganWt
	doc.OrganAddr = organList.OrganAddr
	doc.OrganAddrTxt = organList.OrganAddrTxt
	//获取用户当前的位置
	var pp MemberPosition
	pIn, _ := pp.GetByIdOrOpenId(mid, openId)
	// 查询用户距离
	doc.LocationKm = tools.GetMemberLocation(pIn.MemberLt, pIn.MemberWt, doc.OrganLt, doc.OrganWt)

	return doc, nil
}

func (e *Course) GetById(id int) (Course, error) {

	var doc Course

	//cache 读取 然后返回
	cacheKey := fmt.Sprintf("course:%d", id)
	if foo, ok := cache.GoLocalCache.Get(cacheKey); ok {
		l, _ := foo.(Course)
		return l, nil
	}

	table := orm.Eloquent.Table(e.TableName()).Select("course.*,organ.organ_name,organ.organ_brand as brand_name")
	table = table.Joins("inner join organ on  `organ`.organ_id = course.organ_id")
	table = table.Where("`course`.course_id = ?", id)

	if err := table.First(&doc).Error; err != nil {
		return doc, err
	}

	var dict DictData
	doc.CourseFeature = dict.CodeToValue("sys_organ_feature", doc.CourseFeature)
	doc.CourseCategory = dict.CodeToValue("sys_course_category", doc.CourseCategory)
	doc.CourseTeach = dict.CodeToValue("sys_course_teach_way", doc.CourseTeach)
	doc.CourseAge = dict.CodeToValue("sys_student_age", doc.CourseTeach)

	// 写入cache
	cache.GoLocalCache.Set(cacheKey, doc, 5*time.Minute)

	return doc, nil
}

// 获取Course
func (e *Course) Get() (Course, error) {
	var doc Course
	table := orm.Eloquent.Table(e.TableName()).Select("course.*,organ.organ_name,organ.organ_brand as brand_name")
	table = table.Joins("inner join organ on  `organ`.organ_id = course.organ_id")
	if e.CourseId != 0 {
		table = table.Where("`course`.course_id = ?", e.CourseId)
	}
	if e.CourseName != "" {
		table = table.Where("`course`.course_name like ?", "%"+e.CourseName+"%")
	}
	if e.CourseStatus != "" {
		table = table.Where("`course`.course_status = ?", e.CourseStatus)
	}
	if e.CourseType != "" {
		table = table.Where("course_type = ?", e.CourseType)
	}
	if e.OrganId != 0 {
		table = table.Where("organ_id = ?", e.OrganId)
	}
	if e.OrganName != "" {
		table = table.Where("organ_name = ?", e.OrganName)
	}
	if e.CourseTeach != "" {
		table = table.Where("course_teach = ?", e.CourseTeach)
	}
	if err := table.First(&doc).Error; err != nil {
		return doc, err
	}
	return doc, nil
}

func (e *Course) GetFromGateway() (Course, error) {
	var doc Course
	table := orm.Eloquent.Table(e.TableName()).Select("course.*,organ.organ_name,organ.organ_brand as brand_name")
	table = table.Joins("inner join organ on  `organ`.organ_id = course.organ_id")
	if e.CourseId != 0 {
		table = table.Where("`course`.course_id = ?", e.CourseId)
	}
	if e.CourseName != "" {
		table = table.Where("`course`.course_name like ?", "%"+e.CourseName+"%")
	}
	table = table.Where("`course`.course_status = 5")

	if err := table.First(&doc).Error; err != nil {
		return doc, err
	}

	doc.CompareInfo = getCompareInfo(doc.CourseId)

	return doc, nil
}

type CourseSearch struct {
	CourseStatus    string `json:"courseStatus"`     // 核准状态 1 待审核 ，3 失败 ， 5 已审核
	CourseCategory  string `json:"courseCategory" `  //
	CourseFinish    string `json:"courseFinish" `    //
	CourseExpensive string `json:"courseExpensive" ` // 是否 贵就赔 1 是 / 0 否
	BrandName       string `json:"brandName" `       //
	OrganName       string `json:"organName" `       // 机构名称
	CourseName      string `json:"courseName" `      // 机构名称
	KeyWord         string `json:"keyWord" `         // 机构名称
	LocationKm      string `json:"locationKm" `      // 距离搜索
	LocationKmType  string `json:"locationKmType" `  // 距离搜索
	CourseType      string `json:"courseType" `      // 课程类目 课程类别  素质教育
	CourseTeach     string `json:"courseTeach" `     // 授课方式 ：线上 、 线下
	CourseAge       string `json:"courseAge"`        // 授课适合年龄 1 :0～3岁 3 :3～6岁 6 :7-12岁 9:12-18岁  12: 18岁+
	MemberId        int    `json:"memberId" `
	ThirdUserId     int    `json:"thirdUserId" `
	OpenId          string `json:"openId" `
	CourseTime      string `json:"courseTime" `
	PriceStart      string `json:"priceStart" `
	PriceEnd        string `json:"priceEnd" `
	PriceSort       string `json:"priceSort" `
}

type CourseReq struct {
	CourseId        int     `json:"courseId"  `        // 主键id
	OrganName       string  `json:"organName"  `       // 机构名称
	CourseType      string  `json:"courseType"  `      // 课程类目 课程类别  素质教育
	CourseCategory  string  `json:"courseCategory"  `  // 学科科目 语文/数学
	CourseName      string  `json:"courseName"  `      // 课程名称
	OrganId         int     `json:"organId"  `         // 授课机构
	CourseTeach     string  `json:"courseTeach"  `     // 授课方式 ：线上 、 线下
	OrganFeature    string  `json:"organFeature"  `    // 授课方式 ：线上 、 线下
	CourseExpensive string  `json:"courseExpensive"  ` // 是否 贵就赔 1 是 / 0 否
	CoursePrice     float64 `json:"coursePrice"  `     // 授课金额
	DiscountPrice   float64 `json:"discountPrice"  `   // 优惠金额
	CourseTime      string  `json:"courseTime"  `      // 授课时间 字符串
	CourseAge       string  `json:"courseAge"  `       // 授课适合年龄 1 :0～3岁 3 :3～6岁 6 :7-12岁 9:12-18岁  12: 18岁+
	CourseVideo     string  `json:"courseVideo" `      // 介绍视频 json
	CourseImg       string  `json:"courseImg"  `       // 介绍图片 json
	CourseFeature   string  `json:"courseFeature"  `   // 介绍图片 json
	BrandName       string  `json:"brandName" `        // 品牌名称
	CourseTag       string  `json:"courseTag" `        //标签
	OrganLt         string  `json:"organLt" `          // 经纬度   -- 经度
	OrganWt         string  `json:"organWt"  `         // 经纬度   -- 纬度
	CourseFinish    string  `json:"courseFinish"`      // 课程完成度
	LocationKm      string  `json:"locationKm"`        // 课程完成度
	ContrastStatus  string  `json:"contrastStatus"`    // 加入课程对比状态
	ContrastId      int     `json:"contrastId"`        // 加入课程对比状态
	Distance        float64 `json:"distance"`          // 加入课程对比状态

}

func (e *Course) GetPageSearch(pageSize int, pageIndex int, ss CourseSearch) ([]CourseReq, int, error) {
	var doc []Course

	table := orm.Eloquent.Select("`course`.*,`organ`.organ_name,`organ`.organ_brand as brand_name").Table(e.TableName())
	table = table.Joins("inner join `organ` on `organ`.organ_id = `course`.organ_id")

	if ss.KeyWord != "" {
		keyWord := ss.KeyWord
		table = table.Where("course.course_name like ? OR course.course_type like ? OR course.course_category like ? OR organ.organ_name like ? OR organ.organ_brand like ? OR  course.course_teach like ?",
			"%"+keyWord+"%", "%"+keyWord+"%", "%"+keyWord+"%", "%"+keyWord+"%", "%"+keyWord+"%", "%"+keyWord+"%")
	}

	//距离   locationKm
	start := 0.0
	end := 0.0

	if ss.PriceSort != "1" && ss.PriceSort != "2" {
		if ss.LocationKm != "" || ss.LocationKmType != "" {
			if ss.LocationKmType == "1" {
				start = 0
				end = 0.5
			}
			if ss.LocationKmType == "2" {
				start = 0.5
				end = 2
			}
			if ss.LocationKmType == "3" {
				start = 2
				end = 5
			}
			if ss.LocationKmType == "4" {
				start = 5
				end = 1000000
			}
			//当前用户位置 与 机构 距离 位置
			var pp MemberPosition
			pp.OpenId = ss.OpenId
			pp.MemberId = ss.MemberId
			organIds := pp.GetOrgansArrV2(end, start)

			if len(organIds) > 0 {
				ids := make([]int, len(organIds))
				for _, v := range organIds {
					ids = append(ids, v.OrganId)
				}
				table = table.Where("`course`.organ_id in (?)", ids)
			} else {
				// 未匹配到 机构
				lognew.Info(context.TODO(), "没有数据", lognew.Fields{"ss": ss})

				if ss.LocationKmType != "" {
					table = table.Where("`course`.organ_id in (-1)")
				}
			}
		} else {
			//当前用户位置 与 机构 距离 位置
			var pp MemberPosition
			pp.OpenId = ss.OpenId
			pp.MemberId = ss.MemberId
			organIds := pp.GetOrgansArrV2(10000, 0)

			if len(organIds) > 0 {
				ids := make([]int, len(organIds))
				for _, v := range organIds {
					ids = append(ids, v.OrganId)
				}
				table = table.Where("`course`.organ_id in (?)", ids)
			} else {

				lognew.Info(context.TODO(), "当前用户位置-没有数据", lognew.Fields{"ss": ss})

				//table = table.Where("`course`.organ_id in (-1)")
			}
		}
	}

	//顶部搜索:
	//科目    courseCategory
	if ss.CourseCategory != "" {
		table = table.Where("`course`.course_category = ?", ss.CourseCategory)
	}
	//年龄   courseAge
	if ss.CourseAge != "" {
		table = table.Where("`course`.course_age = ?", ss.CourseAge)
	} else {
		// 按用户年龄纬度进行搜索

	}

	//价格   priceStart   priceEnd
	if ss.PriceStart != "" {
		table = table.Where("`course`.course_price >= ?", ss.PriceStart)
	}
	if ss.PriceEnd != "" {
		table = table.Where("`course`.course_price <= ?", ss.PriceEnd)
	}
	//完成度  courseFinish
	if ss.CourseFinish != "" {
		//  1  60 ， 2 60-80 3 80+
		if ss.CourseFinish == "1" {

			table = table.Where("`course`.course_finish <= 60")
		} else if ss.CourseFinish == "2" {

			table = table.Where("`course`.course_finish >= 60 AND `course`.course_finish <= 80")
		} else if ss.CourseFinish == "3" {

			table = table.Where("`course`.course_finish >= 80")
		}
	}
	if ss.CourseExpensive == "1" {
		table = table.Where("`course`.course_expensive = ?", ss.CourseExpensive)
	}

	if ss.CourseName != "" {
		table = table.Where("`course`.course_name like ?", "%"+ss.CourseName+"%")
	}
	if ss.CourseType != "" && ss.CourseType != "0" {
		table = table.Where("`course`.course_type = ?", ss.CourseType)
	}
	if ss.OrganName != "" {
		table = table.Where("`organ`.organ_name like ?", "%"+ss.OrganName+"%")
	}
	if ss.BrandName != "" {
		table = table.Where("`organ`.organ_brand like ?", "%"+ss.BrandName+"%")
	}
	if ss.CourseTeach != "" && ss.CourseTeach != "0" {
		table = table.Where("`course`.course_teach = ?", ss.CourseTeach)
	}

	if ss.CourseTime != "" {
		table = table.Where("`course`.course_time = ?", ss.CourseTime)
	}

	table = table.Where("`course`.course_status = ?", "5")
	var count int

	orderStr := " `course`.`updated_at` DESC "
	if ss.PriceSort == "2" {
		orderStr = "`course`.`real_price` DESC  ,  `course`.`updated_at` DESC "
	} else if ss.PriceSort == "1" {
		orderStr = " `course`.`real_price` ASC , `course`.`updated_at` DESC"
	}
	if err := table.Order(orderStr, true).Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Error; err != nil {
		return nil, 0, err
	}
	table.Where(" `course`.`deleted_at` IS NULL").Count(&count)

	//處理數據
	l := len(doc)
	if l > 0 {
		var organIds []int
		var courseIds []int
		for i := 0; i < l; i++ {
			organIds = append(organIds, doc[i].OrganId)
			courseIds = append(courseIds, doc[i].CourseId)
		}
		//批量查詢
		var organM Organ
		organList, err := organM.BatchGetBrandNameV2(organIds)
		var contrast MemberContrast
		contrast.MemberId = ss.MemberId
		contrast.ThirdUserId = ss.ThirdUserId
		newlist, err2 := contrast.BatchGetBrandNameV2(courseIds)
		if err == nil {
			for i := 0; i < l; i++ {
				oid := doc[i].OrganId
				doc[i].BrandName = organList[oid].OrganBrand
				doc[i].OrganFeature = organList[oid].OrganFeature
				doc[i].OrganLt = organList[oid].OrganLt
				doc[i].OrganWt = organList[oid].OrganWt
				if err2 == nil {
					cid := doc[i].CourseId
					doc[i].ContrastStatus = newlist[cid].ContrastStatus
					doc[i].ContrastId = newlist[cid].ContrastId
				}
			}
		}
	}

	//获取用户当前的位置
	var pp MemberPosition
	pIn, _ := pp.GetByIdOrOpenId(ss.MemberId, ss.OpenId)

	var docNew myvalue2
	if len(doc) > 0 {
		var dict DictData
		for i := 0; i < len(doc); i++ {
			nl := doc[i]
			km := tools.GetMemberLocation(pIn.MemberLt, pIn.MemberWt, nl.OrganLt, nl.OrganWt)

			if nl.CourseFinish == "" {
				nl.CourseFinish = "80"
			}
			dis, _ := strconv.ParseFloat(km, 64)
			ll := CourseReq{
				CourseId:        nl.CourseId,
				OrganName:       nl.OrganName,
				CourseType:      dict.CodeToValue("sys_course_type", nl.CourseType),
				CourseCategory:  dict.CodeToValue("sys_course_category", nl.CourseCategory),
				CourseName:      nl.CourseName,
				OrganId:         nl.OrganId,
				CourseTeach:     dict.CodeToValue("sys_course_teach_way", nl.CourseTeach), //gateway list
				CourseExpensive: nl.CourseExpensive,
				CoursePrice:     nl.CoursePrice,
				DiscountPrice:   nl.DiscountPrice,
				CourseTime:      nl.CourseTime,
				CourseAge:       dict.CodeToValue("sys_student_age", nl.CourseAge),
				CourseVideo:     nl.CourseVideo,
				CourseImg:       nl.CourseImg,
				CourseFeature:   dict.CodeToValue("sys_organ_feature", nl.CourseFeature),
				BrandName:       nl.BrandName,
				OrganFeature:    nl.OrganFeature,
				OrganLt:         nl.OrganLt,
				OrganWt:         nl.OrganWt,
				ContrastStatus:  nl.ContrastStatus,
				ContrastId:      nl.ContrastId,
				LocationKm:      km,
				Distance:        dis,
				CourseFinish:    nl.CourseFinish,
				CourseTag:       "精品好课,优惠",
			}
			docNew = append(docNew, ll)
		}
	}

	if ss.PriceSort != "1" && ss.PriceSort != "2" {
		// 数组按 distance 排序
		sort.Sort(docNew)
	}
	return docNew, count, nil
}

type myvalue2 []CourseReq

func (p myvalue2) Len() int {
	return len(p)
}

// 想了想能用循环，实现所有字段比对一次，更精确点，免得二维数组的元素前面n个元素都是一样的
func (p myvalue2) Less(i, j int) bool {
	for k := 0; k < len(p); k++ {
		if p[i].Distance > p[j].Distance {
			return true
		} else if p[i].Distance == p[j].Distance {
			continue
		} else {
			return false
		}
	}
	return true
}

func (p myvalue2) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}

func (e *Course) GetFiancePage(pageSize int, pageIndex int) ([]CourseNew, int, error) {
	var doc []CourseNew

	table := orm.Eloquent.Select("course.*,organ.organ_name,organ.organ_brand as brand_name").Table(e.TableName())
	table = table.Joins("inner join organ on  `organ`.organ_id = course.organ_id")
	if e.CourseId != 0 {
		table = table.Where("course.course_id = ?", e.CourseId)
	}
	if e.CourseName != "" {
		table = table.Where("course.course_name like ?", "%"+e.CourseName+"%")
	}
	if e.CourseStatus != "" {
		table = table.Where("course.course_status = ?", e.CourseStatus)
	}
	if e.CourseType != "" {
		table = table.Where("course.course_type = ?", e.CourseType)
	}
	if e.CourseCategory != "" {
		table = table.Where("course.course_category = ?", e.CourseCategory)
	}
	if e.OrganId != 0 {
		table = table.Where("course.organ_id = ?", e.OrganId)
	}
	if e.OrganName != "" {
		table = table.Where("organ.organ_name like ?", "%"+e.OrganName+"%")
	}
	if e.BrandName != "" {
		table = table.Where("organ.organ_brand like ?", "%"+e.BrandName+"%")
	}
	if e.CourseTeach != "" {
		table = table.Where("course.course_teach = ?", e.CourseTeach)
	}
	if e.CourseTime != "" {
		table = table.Where("course.course_time = ?", e.CourseTime)
	}
	if e.CourseAge != "" {
		table = table.Where("course.course_age = ?", e.CourseAge)
	}
	if e.CreateBy != "" {
		table = table.Where("course.create_by = ?", e.CreateBy)
	}
	if e.UpdateBy != "" {
		table = table.Where("course.update_by = ?", e.UpdateBy)
	}
	if e.CourseFinish != "" {
		table = table.Where("course.course_finish >= ?", e.CourseFinish)
	}
	//data.UpdateStart
	if e.UpdateStart != "" {
		table = table.Where("course.updated_at >= ?", e.UpdateStart)
	}
	if e.UpdateEnd != "" {
		table = table.Where("course.updated_at <= ?", e.UpdateEnd)
	}

	// 数据权限
	table, _ = HandleOrganCommonTable(table, "course", e.DataScope, "机构财务列表") // 分佣金列表

	var count int

	if err := table.Order(" `course`.`updated_at` DESC", true).Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Error; err != nil {
		return nil, 0, err
	}
	table.Where("course.deleted_at IS NULL").Count(&count)

	//處理數據
	l := len(doc)
	if l > 0 {
		var organIds []int
		for i := 0; i < l; i++ {
			organId := doc[i].OrganId
			organIds = append(organIds, organId)
		}
		//批量查詢
		var organM Organ
		organList, err := organM.BatchGetBrandName(organIds)
		if err == nil {
			for i := 0; i < l; i++ {
				oid := doc[i].OrganId
				doc[i].BrandName, _ = organList[oid]
			}
		}
	}
	return doc, count, nil
}

// gateway 查询 机构下课程列表
func (e *Course) GetSearchPage(pageSize int, pageIndex int) ([]Course, int, error) {
	var doc []Course

	table := orm.Eloquent.Select("course.*,organ.organ_name,organ.organ_brand as brand_name").Table(e.TableName())
	table = table.Joins("inner join organ on  `organ`.organ_id = course.organ_id")
	if e.CourseId != 0 {
		table = table.Where("course.course_id = ?", e.CourseId)
	}
	if e.CourseName != "" {
		table = table.Where("course.course_name like ?", "%"+e.CourseName+"%")
	}
	if e.CourseStatus != "" {
		table = table.Where("course.course_status = ?", e.CourseStatus)
	}
	if e.CourseType != "" {
		table = table.Where("course.course_type = ?", e.CourseType)
	}
	if e.CourseCategory != "" {
		table = table.Where("course.course_category = ?", e.CourseCategory)
	}
	if e.OrganId != 0 {
		table = table.Where("course.organ_id = ?", e.OrganId)
	}
	if e.OrganName != "" {
		table = table.Where("organ.organ_name like ?", "%"+e.OrganName+"%")
	}
	if e.BrandName != "" {
		table = table.Where("organ.organ_brand like ?", "%"+e.BrandName+"%")
	}
	if e.CourseTeach != "" {
		table = table.Where("course.course_teach = ?", e.CourseTeach)
	}
	if e.CourseTime != "" {
		table = table.Where("course.course_time = ?", e.CourseTime)
	}
	if e.CourseAge != "" {
		table = table.Where("course.course_age = ?", e.CourseAge)
	}
	if e.CourseFinish != "" {
		table = table.Where("course.course_finish >= ?", e.CourseFinish)
	}
	//data.UpdateStart
	if e.UpdateStart != "" {
		table = table.Where("course.updated_at >= ?", e.UpdateStart)
	}
	if e.UpdateEnd != "" {
		table = table.Where("course.updated_at <= ?", e.UpdateEnd)
	}

	var count int

	if err := table.Order(" `course`.`updated_at` DESC", true).Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Error; err != nil {
		return nil, 0, err
	}
	table.Where("course.deleted_at IS NULL").Count(&count)

	//處理數據
	l := len(doc)
	if l > 0 {
		var organIds []int
		for i := 0; i < l; i++ {
			organId := doc[i].OrganId
			organIds = append(organIds, organId)
		}
		//批量查詢
		var organM Organ
		organList, err := organM.BatchGetBrandName(organIds)
		if err == nil {
			for i := 0; i < l; i++ {
				oid := doc[i].OrganId
				doc[i].BrandName, _ = organList[oid]
			}
		}
	}
	return doc, count, nil
}

// 获取Course带分页
func (e *Course) GetPage(pageSize int, pageIndex int) ([]Course, int, error) {
	var doc []Course

	table := orm.Eloquent.Select("course.*,organ.organ_name,organ.organ_brand as brand_name").Table(e.TableName())
	table = table.Joins("inner join organ on  `organ`.organ_id = course.organ_id")
	if e.CourseId != 0 {
		table = table.Where("course.course_id = ?", e.CourseId)
	}
	if e.CourseName != "" {
		table = table.Where("course.course_name like ?", "%"+e.CourseName+"%")
	}
	if e.CourseStatus != "" {
		table = table.Where("course.course_status = ?", e.CourseStatus)
	}
	if e.CourseType != "" {
		table = table.Where("course.course_type = ?", e.CourseType)
	}
	if e.CourseCategory != "" {
		table = table.Where("course.course_category = ?", e.CourseCategory)
	}
	if e.OrganId != 0 {
		table = table.Where("course.organ_id = ?", e.OrganId)
	}
	if e.OrganName != "" {
		table = table.Where("organ.organ_name like ?", "%"+e.OrganName+"%")
	}
	if e.BrandName != "" {
		table = table.Where("organ.organ_brand like ?", "%"+e.BrandName+"%")
	}
	if e.CourseTeach != "" {
		table = table.Where("course.course_teach = ?", e.CourseTeach)
	}
	if e.CourseTime != "" {
		table = table.Where("course.course_time = ?", e.CourseTime)
	}
	if e.CourseAge != "" {
		table = table.Where("course.course_age = ?", e.CourseAge)
	}
	if e.CreateBy != "" {
		table = table.Where("course.create_by = ?", e.CreateBy)
	}
	if e.UpdateBy != "" {
		table = table.Where("course.update_by = ?", e.UpdateBy)
	}
	if e.CourseFinish != "" {
		table = table.Where("course.course_finish >= ?", e.CourseFinish)
	}
	//data.UpdateStart
	if e.UpdateStart != "" {
		table = table.Where("course.updated_at >= ?", e.UpdateStart)
	}
	if e.UpdateEnd != "" {
		table = table.Where("course.updated_at <= ?", e.UpdateEnd)
	}

	// 数据权限
	table, _ = HandleOrganCommonTable(table, "course", e.DataScope, "机构课程")

	var count int

	if err := table.Order(" `course`.`updated_at` DESC", true).Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Error; err != nil {
		return nil, 0, err
	}
	table.Where("course.deleted_at IS NULL").Count(&count)

	//處理數據
	l := len(doc)
	if l > 0 {
		var organIds []int
		for i := 0; i < l; i++ {
			organId := doc[i].OrganId
			organIds = append(organIds, organId)
		}
		//批量查詢
		var organM Organ
		var dict DictData
		organList, err := organM.BatchGetBrandName(organIds)
		if err == nil {
			for i := 0; i < l; i++ {
				oid := doc[i].OrganId
				doc[i].BrandName, _ = organList[oid]
				doc[i].CourseCategory = dict.CodeToValue("sys_course_category", doc[i].CourseCategory)
			}
		}
	}
	return doc, count, nil
}

// 更新Course
func (e *Course) Update(id int) (update Course, err error) {
	if err = orm.Eloquent.Table(e.TableName()).Where("course_id = ?", id).First(&update).Error; err != nil {
		return
	}

	//参数1:是要修改的数据
	//参数2:是修改的数据
	if err = orm.Eloquent.Table(e.TableName()).Model(&update).Updates(&e).Error; err != nil {
		return
	}
	return
}

func (e *Course) UpdateCoursePrice(id int, price float64) {
	table := orm.Eloquent.Table(e.TableName())
	table.Exec("UPDATE course SET course_price = ?  WHERE course_id = ?", price, id)
	return
}

func (e *Course) UpdateCourseRealPrice(id int, price float64) {
	table := orm.Eloquent.Table(e.TableName())
	table.Exec("UPDATE course SET real_price = ?  WHERE course_id = ?", price, id)
	return
}

func (e *Course) UpdateDiscountPrice(id int, price float64) {
	table := orm.Eloquent.Table(e.TableName())
	table.Exec("UPDATE course SET discount_price = ?  WHERE course_id = ?", price, id)
	return
}

// 删除Course
func (e *Course) Delete(id int) (success bool, err error) {
	if err = orm.Eloquent.Table(e.TableName()).Where("course_id = ?", id).Delete(&Course{}).Error; err != nil {
		success = false
		return
	}
	success = true
	return
}

//批量删除
func (e *Course) BatchDelete(id []int) (Result bool, err error) {
	if err = orm.Eloquent.Table(e.TableName()).Where("course_id in (?)", id).Delete(&Course{}).Error; err != nil {
		return
	}
	Result = true
	return
}
